﻿/*
*VMukti -- An open source video conferencing platform.
*
* Copyright (C) 2007 - 2008, VMukti Solutions Pvt. Ltd.
*
* Hardik Sanghvi <hardik@vmukti.com>
*
* See http://www.vmukti.com for more information about
* the VMukti project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, forums and mailing lists
* for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlServerCe;
using System.Net;
using VMukti.Business.WCFServices.BootStrapServices.BasicHttp;
using VMukti.Business.WCFServices.BootStrapServices.DataContracts;
using VMukti.Business.WCFServices.SuperNodeServices.DataContract;
using VMukti.Presentation.Domains;
using VMuktiAPI;
using VMuktiService;
using Microsoft.Synchronization.Data;
using Microsoft.Synchronization.Data.SqlServerCe;
using System.IO;

namespace VMukti.Presentation
{
    [Serializable]
    public class BootstrapServiceDomain : IDisposable
    {
        object objHttpBootStrap = null;

        NetPeerServer npsBootStrapServer = null;
        NetPeerServer npsBootStrapPredictviveServer = null;
        NetPeerServer npsBootStrapPBXServer = null;
        NetPeerServer npsBootStrapActiveCallReportService = null;
        NetPeerServer npsBootStrapActiveAgentReportService = null;
        NetPeerServer npsRecordingServer = null;
        NetPeerServer npsConsoleServer = null;

        //ManagerContainer _containerManager = null;

        //SqlCeConnection Conn = null;
        //SqlCeCommand sqlcmd = null;
        //DataTable dt = new DataTable();
        string strCurrentMachineIP = string.Empty;
        string appPath = AppDomain.CurrentDomain.BaseDirectory;
        string awClientConnectionString = null;
        SqlCeConnection LocalSQLConn = null;
        string ClientConnectionString = @"Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "AllocateConferenceNumber.sdf";
        string strLocalDBPath = AppDomain.CurrentDomain.BaseDirectory + "AllocateConferenceNumber.sdf";
        //#region Uploading Recorded Files

        //object objNetP2PRecording = null;
        //INetP2PRecordingCallsServiceChannel clientNetP2pChannelRecording = null;

        //System.IO.FileStream fsR;
        //int flag = 0;

        //int nosignal = 0;
        //double smallPart;
        //byte[] arr = new byte[5000];
        //byte[] Larr;

        //#endregion

        public BootstrapServiceDomain()
        {
            try
            {

                if (!System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory.ToString() + "sqlceme35.dll"))
                {
                    //new WebClient().DownloadFile("http://" + VMuktiAPI.VMuktiInfo.BootStrapIPs[0] + "/VMukti/sqlceme35.dll.zip", AppDomain.CurrentDomain.BaseDirectory.ToString() + "sqlceme35.dll");
                    //new WebClient().DownloadFile("http://" + VMuktiAPI.VMuktiInfo.BootStrapIPs[0] + "/VMukti/sqlceqp35.dll.zip", AppDomain.CurrentDomain.BaseDirectory.ToString() + "sqlceqp35.dll");
                    //new WebClient().DownloadFile("http://" + VMuktiAPI.VMuktiInfo.BootStrapIPs[0] + "/VMukti/sqlcese35.dll.zip", AppDomain.CurrentDomain.BaseDirectory.ToString() + "sqlcese35.dll");
                   
                    
                    new WebClient().DownloadFile(VMuktiAPI.VMuktiInfo.ZipFileDownloadLink + "sqlceme35.dll.zip", AppDomain.CurrentDomain.BaseDirectory.ToString() + "sqlceme35.dll");
                    new WebClient().DownloadFile(VMuktiAPI.VMuktiInfo.ZipFileDownloadLink + "sqlceqp35.dll.zip", AppDomain.CurrentDomain.BaseDirectory.ToString() + "sqlceqp35.dll");
                    new WebClient().DownloadFile(VMuktiAPI.VMuktiInfo.ZipFileDownloadLink + "sqlcese35.dll.zip", AppDomain.CurrentDomain.BaseDirectory.ToString() + "sqlcese35.dll");

                }
                if (!System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory.ToString() + "AllocateConferenceNumber.sdf"))
                {
                    //new WebClient().DownloadFile("http://" + VMuktiAPI.VMuktiInfo.BootStrapIPs[0] + "/VMukti/AllocateConferenceNumber.sdf.zip", AppDomain.CurrentDomain.BaseDirectory.ToString() + "AllocateConferenceNumber.sdf");
                    //  new WebClient().DownloadFile(VMuktiAPI.VMuktiInfo.ZipFileDownloadLink + "AllocateConferenceNumber.sdf.zip", AppDomain.CurrentDomain.BaseDirectory.ToString() + "AllocateConferenceNumber.sdf");
                    SqlCeEngine clientEngine = new SqlCeEngine(ClientConnectionString);
                    clientEngine.CreateDatabase();

                    LocalSQLConn = new SqlCeConnection();
                    LocalSQLConn.ConnectionString = ClientConnectionString;
                    LocalSQLConn.Open();


                    fncCreateSNNodeInfoTable();
                    fncCreateBuddyStatusTable();
                    fncCreateUserBuddyListTable();
                    fncCreateUserSuperNode_NodeInfoTable();
                    fncCreateUserSuperNodeInfoTable();
                }
                else
                {
                    LocalSQLConn = new SqlCeConnection();
                    LocalSQLConn.ConnectionString = ClientConnectionString;
                    LocalSQLConn.Open();
                }
                awClientConnectionString = @"Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "AllocateConferenceNumber.sdf";
                //Conn = new SqlCeConnection(awClientConnectionString);
                //Conn.Open();

                // Changes realted to vista
                //strCurrentMachineIP = System.Net.Dns.GetHostEntry(System.Environment.MachineName).AddressList[0].ToString();
                strCurrentMachineIP = GetIP4Address();
                // End changes

                //if (VMuktiInfo.CurrentPeer.CurrPeerType == PeerType.BootStrap)
                {
                    #region HttpServerHoster

                    objHttpBootStrap = new BootStrapDelegates();
                    ((BootStrapDelegates)objHttpBootStrap).EntHttpAddBuddy += new BootStrapDelegates.DelsvcHttpAddBuddy(BootstrapServiceDomain_EntHttpAddBuddy);
                    ((BootStrapDelegates)objHttpBootStrap).EntHttpRemoveBuddy += new BootStrapDelegates.DelsvcRemoveAddBuddy(BootstrapServiceDomain_EntHttpRemoveBuddy);
                    ((BootStrapDelegates)objHttpBootStrap).EntHttpBsGetSuperNodeIP += new BootStrapDelegates.DelsvcHttpBsGetSuperNodeIP(BootstrapServiceDomain_EntHttpBsGetSuperNodeIP);
                    ((BootStrapDelegates)objHttpBootStrap).EntHttpBSJoin += new BootStrapDelegates.DelHttpBSJoin(BootstrapServiceDomain_EntHttpBSJoin);
                    ((BootStrapDelegates)objHttpBootStrap).EntHttpBSUnJoin += new BootStrapDelegates.DelsvcHttpBSUnJoin(BootstrapServiceDomain_EntHttpBSUnJoin);
                    ((BootStrapDelegates)objHttpBootStrap).EntHttpGetSuperNodeBuddyList += new BootStrapDelegates.DelsvcHttpGetSuperNodeBuddyList(BootstrapServiceDomain_EntHttpGetSuperNodeBuddyList);
                    ((BootStrapDelegates)objHttpBootStrap).EntHttpBSAuthorizedUser += new BootStrapDelegates.DelsvcHttpBSAuthorizedUser(BootstrapServiceDomain_EntHttpBSAuthorizedUser);

                    ((BootStrapDelegates)objHttpBootStrap).EntsvcGetNodeNameByIP += new BootStrapDelegates.DelsvcGetNodeNameByIP(BootstrapServiceDomain_EntsvcGetNodeNameByIP);
                    ((BootStrapDelegates)objHttpBootStrap).EntHTTPGetOfflineNodeName += new BootStrapDelegates.DelsvcGetOfflineNodeName(BootstrapServiceDomain_EntHTTPGetOfflineNodeName);

                    //VMuktiInfo.BootStrapIPs.Add("192.168.1.24");
                    BasicHttpServer bhsHttpBootStrap = new BasicHttpServer(ref objHttpBootStrap, "http://" + VMuktiInfo.BootStrapIPs[0] + ":80/HttpBootStrap");
                    bhsHttpBootStrap.AddEndPoint<IHTTPBootStrapService>("http://" + VMuktiInfo.BootStrapIPs[0] + ":80/HttpBootStrap");
                    bhsHttpBootStrap.OpenServer();

                    #endregion

                    #region NetP2PServerHoster
                    npsBootStrapServer = new NetPeerServer("net.tcp://" + VMuktiInfo.BootStrapIPs[0] + ":4000/NetP2PBootStrap");
                    npsBootStrapServer.AddEndPoint("net.tcp://" + VMuktiInfo.BootStrapIPs[0] + ":4000/NetP2PBootStrap");
                    npsBootStrapServer.OpenServer();
                    //MessageBox.Show("netp2p server hosted");
                    #endregion

                    #region NetP2PConsoleServerHoster

                    npsConsoleServer = new NetPeerServer("net.tcp://" + VMuktiAPI.VMuktiInfo.BootStrapIPs[0] + ":6000/NetP2PConsole");
                    npsConsoleServer.AddEndPoint("net.tcp://" + VMuktiAPI.VMuktiInfo.BootStrapIPs[0] + ":6000/NetP2PConsole");
                    npsConsoleServer.OpenServer();


                    #endregion


                    #region CallCenter Services
                    //#region NetP2PPrictiveServerHoster
                    //npsBootStrapPredictviveServer = new NetPeerServer("net.tcp://" + VMuktiInfo.BootStrapIPs[0] + ":6000/NetP2PBootStrapPredictive");
                    //npsBootStrapPredictviveServer.AddEndPoint("net.tcp://" + VMuktiInfo.BootStrapIPs[0] + ":6000/NetP2PBootStrapPredictive");
                    //npsBootStrapPredictviveServer.OpenServer();
                    //#endregion

                    //#region NetP2PPBXServerHoster
                    ////npsBootStrapPBXServer = new NetPeerServer("net.tcp://" + VMuktiInfo.BootStrapIPs[0] + ":6001/NetP2PBootStrapPBX");
                    ////npsBootStrapPBXServer.AddEndPoint("net.tcp://" + VMuktiInfo.BootStrapIPs[0] + ":6001/NetP2PBootStrapPBX");
                    ////npsBootStrapPBXServer.OpenServer();
                    //#endregion


                    //#region Service For Report Application

                    //npsBootStrapActiveCallReportService = new NetPeerServer("net.tcp://" + VMuktiInfo.BootStrapIPs[0] + ":4000/NetP2PBootStrapActiveCallReport");
                    //npsBootStrapActiveCallReportService.AddEndPoint("net.tcp://" + VMuktiInfo.BootStrapIPs[0] + ":4000/NetP2PBootStrapActiveCallReport");
                    //npsBootStrapActiveCallReportService.OpenServer();

                    //#endregion

                    //# region Service For Active Agent Report
                    //npsBootStrapActiveAgentReportService = new NetPeerServer("net.tcp://" + VMuktiInfo.BootStrapIPs[0] + "4000/NetP2PBootStrapActiveAgentReport");
                    //npsBootStrapActiveAgentReportService.AddEndPoint("net.tcp://" + VMuktiInfo.BootStrapIPs[0] + ":4000/NetP2PBootStrapActiveAgentReport");
                    //npsBootStrapActiveAgentReportService.OpenServer();
                    //#endregion


                    //#region Server For Uploading Recorded Calls


                    //npsRecordingServer = new NetPeerServer("net.tcp://" + VMuktiInfo.BootStrapIPs[0] + ":4000/NetP2PRecording");
                    //npsRecordingServer.AddEndPoint("net.tcp://" + VMuktiInfo.BootStrapIPs[0] + ":4000/NetP2PRecording");
                    //npsRecordingServer.OpenServer();

                    //#endregion


                    //#region Client For Uploading Recorded Calls

                    //NetPeerClient npcRecordingClient = new NetPeerClient();
                    //objNetP2PRecording = new NetP2PRecordingCallsDelegates();

                    //((NetP2PRecordingCallsDelegates)objNetP2PRecording).EntsvcNetP2PRecordingServiceJoin += new NetP2PRecordingCallsDelegates.DelsvcNetP2PRecordingServiceJoin(BootstrapServiceDomain_EntsvcNetP2PRecordingServiceJoin);
                    //((NetP2PRecordingCallsDelegates)objNetP2PRecording).EntsvcNetP2PSendRecordedFile += new NetP2PRecordingCallsDelegates.DelsvcNetP2PSendRecordedFile(BootstrapServiceDomain_EntsvcNetP2PSendRecordedFile);
                    //((NetP2PRecordingCallsDelegates)objNetP2PRecording).EntsvcNetP2PReceiveRecordedFile += new NetP2PRecordingCallsDelegates.DelsvcNetP2PReceiveRecordedFile(BootstrapServiceDomain_EntsvcNetP2PReceiveRecordedFile);
                    //((NetP2PRecordingCallsDelegates)objNetP2PRecording).EntsvcNetP2PUnJoin += new NetP2PRecordingCallsDelegates.DelsvcNetP2PRecordingUnJoin(BootstrapServiceDomain_EntsvcNetP2PUnJoin);

                    ////VMuktiAPI.VMuktiInfo.BootStrapIPs.Add("192.168.1.24");

                    //clientNetP2pChannelRecording = (INetP2PRecordingCallsServiceChannel)npcRecordingClient.OpenClient<INetP2PRecordingCallsServiceChannel>("net.tcp://" + VMuktiInfo.BootStrapIPs[0] + ":4000/NetP2PRecording", "P2PRecordingCallsMesh", ref objNetP2PRecording);
                    //clientNetP2pChannelRecording.svcNetP2PRecordingServiceJoin();
                    ////MessageBox.Show("clientNetP2pChannelBS is open");

                    //#endregion
                    #endregion


                }
            }
            catch (Exception ex)
            {
                //System.Windows.Forms.MessageBox.Show("BootStrap Node Service Domain :: " + exp.Message);
                ex.Data.Add("My Key", "BootStrapdomain()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        List<string> lstsSuperNodeInfo = new List<string>();
        List<string> localSuperNodeInfo = new List<string>();
        bool isFirstTime;
        string BootstrapServiceDomain_EntHTTPGetOfflineNodeName(string uName, string IP)
        {
            try
            {
                if (!isFirstTime)
                {
                    isFirstTime = true;
                    foreach (string str in lstsSuperNodeInfo)
                    {
                        localSuperNodeInfo.Add(str);
                    }
                    //localSuperNodeInfo = lstsSuperNodeInfo;
                }
                if (localSuperNodeInfo.Contains(uName))
                {
                    localSuperNodeInfo.Remove(uName);
                }

                if (localSuperNodeInfo.Count == 1)
                {
                    isFirstTime = false;
                    string strUname = localSuperNodeInfo[0];
                    localSuperNodeInfo.Clear();
                    fncSNInsertBuddy(strUname, "Offline");
                    fncSNDeleteNode(strUname);
                    fncUpdateUserBuddyStatus(strUname, "Offline");
                    lstsSuperNodeInfo.Remove(strUname);
                    return strUname;
                }
                else
                {
                    return uName;
                }
            }
            catch (Exception ex)
            {
                //System.Windows.Forms.MessageBox.Show("BootStrap Node Service Domain :: " + exp.Message);
                ex.Data.Add("My Key", "BootstrapServiceDomain_EntHTTPGetOfflineNodeName()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
                return string.Empty;
            }
        }

        string BootstrapServiceDomain_EntsvcGetNodeNameByIP(string NodeIP)
        {
            try
            {
               // SqlCeConnection conn = new SqlCeConnection(ClientConnectionString);
               // conn.Open();
                OpenConnection();
                string cmdString = "Select SuperNodeName from  SuperNode_Info where SuperNodeIP='" + NodeIP + "' ";
                SqlCeCommand NodeSel = new SqlCeCommand(cmdString, LocalSQLConn);
                //ExecuteScalar("Select Node_Name from  SuperNode_Node_Info where SuperNode_Id='" + PreSupIP + "' ;", CommandType.Text, null);
                //string NodeName = NodeSel.ExecuteScalar().ToString();
                object NodeName = NodeSel.ExecuteScalar();
              //  conn.Close();
                return (string)NodeName;
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "BootStrapdomain()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
                return null;
            }
        }     

        string GetIP4Address()
        {
            string IP4Address = String.Empty;
            try
            {
                foreach (IPAddress IPA in Dns.GetHostAddresses(System.Net.Dns.GetHostName()))
                {
                    if (IPA.AddressFamily.ToString() == "InterNetwork")
                    {
                        IP4Address = IPA.ToString();
                        break;
                    }
                }
                return IP4Address;
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "GetIP4Address--:-BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
                return IP4Address;

            }
        }


        //#region WCF Events For Uploading Recorded Files

        //void BootstrapServiceDomain_EntsvcNetP2PUnJoin()
        //{

        //}

        //void BootstrapServiceDomain_EntsvcNetP2PReceiveRecordedFile(string strFileName, byte[] bytearr, int intSig)
        //{
        //    try
        //    {
        //        if (fsR == null && flag == 0 && nosignal == 0)
        //        {
        //            fsR = new System.IO.FileStream(Environment.SpecialFolder.ProgramFiles.ToString() + "\\Default Company Name\\VMukti\\Adiance\\RecordedFiles" + strFileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);
        //            fsR.Close();
        //            fsR = File.OpenWrite(Environment.SpecialFolder.ProgramFiles.ToString() + "\\Default Company Name\\VMukti\\Adiance\\RecordedFiles" + strFileName);
        //            fsR.Position = fsR.Length;
        //            fsR.Write(arr, 0, arr.Length);
        //            fsR.Close();
        //            if (intSig == 1)
        //            {
        //                fsR.Dispose();
        //                fsR = null;
        //                nosignal = 0;
        //                //channelNetTcp.svcRecResponse(receiver, sender, FileName, flag, signal);
        //            }

        //        }
        //        else if (fsR != null && flag == 0)
        //        {
        //            fsR = File.OpenWrite(Environment.SpecialFolder.ProgramFiles.ToString() + "\\Default Company Name\\VMukti\\Adiance\\RecordedFiles");

        //            fsR.Position = fsR.Length;
        //            fsR.Write(arr, 0, arr.Length);
        //            fsR.Close();
        //            if (intSig == 1)
        //            {
        //                fsR.Dispose();
        //                fsR = null;
        //                nosignal = 0;
        //                intSig = 0;
        //                //channelNetTcp.svcRecResponse(receiver, sender, FileName, flag, signal);
        //            }
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        //MessageBox.Show("BootstrapServiceDomain_EntsvcNetP2PReceiveRecordedFile " + exp.Message);
        //        ex.Data.Add("My Key", "BootstrapServiceDomain_EntsvcNetP2PReceiveRecordedFile()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
        //        ClsException.LogError(ex);
        //    }
        //}

        //void BootstrapServiceDomain_EntsvcNetP2PSendRecordedFile(string strFileName, byte[] bytearr)
        //{

        //}
        //void BootstrapServiceDomain_EntsvcNetP2PRecordingServiceJoin()
        //{

        //}
        //#endregion


        #region Buddy Related HttpBootStrap Events Handlers HTTP & NetP2P

        VMukti.Business.WCFServices.BootStrapServices.DataContracts.clsBootStrapInfo BootstrapServiceDomain_EntHttpBSJoin(string uName, clsPeerInfo objPeerInformation)
        {
            //SqlCeConnection Conn = new SqlCeConnection(awClientConnectionString);
            //Conn.Open();
            //DataTable dt = new DataTable();
            //SqlCeCommand sqlcmd = null;
            try
            {
                clsBootStrapInfo objBootStrapInfo = new clsBootStrapInfo();

                objBootStrapInfo.AuthServerIP = VMuktiInfo.CurrentPeer.AuthServerIP;
                objBootStrapInfo.AuthType = VMuktiAPI.VMuktiInfo.CurrentPeer.CurrAuthType.ToString();
                objBootStrapInfo.ConnectionString = VMuktiAPI.VMuktiInfo.MainConnectionString;

                //if (objPeerInformation.objPeerInforation.CurrPeerType == PeerType.NodeWithHttp)
                //{
                //    if (VMuktiAPI.VMuktiInfo.CurrentPeer.CurrAuthType == AuthType.SIPAuthentication)
                //    {
                //        sqlcmd = new SqlCeCommand("SELECT SIP_Number FROM SIP_Info WHERE UserName='" + uName + "'");
                //        sqlcmd.Connection = Conn;
                //        object objSIPInfo = sqlcmd.ExecuteScalar();

                //        if (objSIPInfo != null)
                //        {
                //            objBootStrapInfo.SIPUserNumber = objSIPInfo.ToString();
                //        }
                //        else
                //        {
                //            objBootStrapInfo.SIPUserNumber = "";
                //        }

                //        if (objPeerInformation.objPeerInforation.Port5060Status == PortStatus.InOutBoundClosed)
                //        {
                //            sqlcmd = new SqlCeCommand("SELECT count(*) FROM SuperNode_Info");
                //            sqlcmd.Connection = Conn;
                //            object objSuperNodeCount = sqlcmd.ExecuteScalar();

                //            objBootStrapInfo.ConnectionString = VMuktiAPI.VMuktiInfo.MainConnectionString;

                //            SqlCeDataAdapter sqlDataAdap = null;
                //            if (int.Parse(objSuperNodeCount.ToString()) > 1)
                //            {
                //                sqlDataAdap = new SqlCeDataAdapter("SELECT * FROM SuperNode_Info WHERE SuperNodeIP <> '" + strCurrentMachineIP + "' ORDER BY NodeCount", Conn);
                //                sqlDataAdap.Fill(dt);
                //                objBootStrapInfo.AuthSuperNodeIP = dt.Rows[0]["SuperNodeIP"].ToString();
                //            }
                //            else
                //            {
                //                sqlDataAdap = new SqlCeDataAdapter("SELECT * FROM SuperNode_Info ORDER BY NodeCount", Conn);
                //                sqlDataAdap.Fill(dt);
                //                objBootStrapInfo.AuthSuperNodeIP = dt.Rows[0]["SuperNodeIP"].ToString();
                //            }
                //        }
                //    }
                //    else if (VMuktiAPI.VMuktiInfo.CurrentPeer.CurrAuthType == AuthType.SQLAuthentication)
                //    {
                //        sqlcmd = new SqlCeCommand("SELECT count(*) FROM SuperNode_Info");
                //        sqlcmd.Connection = Conn;
                //        object objSuperNodeCount = sqlcmd.ExecuteScalar();

                //        SqlCeDataAdapter sqlDataAdap = null;
                //        if (int.Parse(objSuperNodeCount.ToString()) > 1)
                //        {
                //            sqlDataAdap = new SqlCeDataAdapter("SELECT * FROM SuperNode_Info WHERE SuperNodeIP <> '" + strCurrentMachineIP + "' ORDER BY NodeCount", Conn);
                //            sqlDataAdap.Fill(dt);
                //            objBootStrapInfo.AuthSuperNodeIP = dt.Rows[0]["SuperNodeIP"].ToString();
                //        }
                //        else
                //        {
                //            sqlDataAdap = new SqlCeDataAdapter("SELECT * FROM SuperNode_Info ORDER BY NodeCount", Conn);
                //            sqlDataAdap.Fill(dt);
                //            objBootStrapInfo.AuthSuperNodeIP = dt.Rows[0]["SuperNodeIP"].ToString();
                //        }

                //        if (objPeerInformation.objPeerInforation.Port1433Status == PortStatus.InOutBoundClosed)
                //        {

                //        }
                //    }
                //}
                //Conn.Close();
                //Conn.Dispose();
                return objBootStrapInfo;
            }
            catch (Exception ex)
            {
                //MessageBox.Show(exp.Message);
                ex.Data.Add("My Key", "BootstrapServiceDomain_EntHttpBSJoin()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
                //Conn.Close();
                //Conn.Dispose();
                return null;
            }
        }

        List<string> BootstrapServiceDomain_EntHttpGetSuperNodeBuddyList(string uName)
        {
            lock (this)
            {
                List<string> lstOnlineBuddies = new List<string>();
                //  SqlCeConnection conn = new SqlCeConnection(awClientConnectionString);
             //   conn.Open();
                try
                {

                    //SqlCeConnection conn = new SqlCeConnection(ClientConnectionString);
                    //conn.Open();
                    //string str = "SELECT * FROM Node_Status";
                    //SqlCeDataAdapter dataAdapter = new SqlCeDataAdapter(str, conn);   
                    OpenConnection();
                    string str = "SELECT * FROM User_BuddyList Where UserName ='" + uName + "'";
                    SqlCeDataAdapter dataAdapter = new SqlCeDataAdapter(str, LocalSQLConn);

                    DataTable dataTable = new DataTable();
                    dataAdapter.Fill(dataTable);

                    for (int i = 0; i < dataTable.Rows.Count; i++)
                    {
                        lstOnlineBuddies.Add(dataTable.Rows[i]["BuddyName"].ToString() + "-" + dataTable.Rows[i]["BuddyStatus"].ToString());
                    }
                    //   conn.Close();
                    //   conn.Dispose();
                    return lstOnlineBuddies;
                    // End Meet Code.
                }
                catch (Exception ex)
                {
                    //Console.WriteLine(ex.Message);
                    ex.Data.Add("My Key", "BootstrapServiceDomain_EntHttpGetSuperNodeBuddyList()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                    ClsException.LogError(ex);
                    ClsException.WriteToErrorLogFile(ex);
                    //   conn.Close();
                    //   conn.Dispose();
                    return lstOnlineBuddies;
                }
            }
        }

        void BootstrapServiceDomain_EntHttpBSUnJoin(string uName, string IP, bool IsSuperNode)
        {
            //   SqlCeConnection Conn = new SqlCeConnection(awClientConnectionString);
            //  Conn.Open();
            DataTable dt = new DataTable();
            SqlCeCommand sqlcmd = null;
            try
            {
                // Meet Code For Buddylist Implementation.
                if (uName != null && uName != string.Empty && uName != IP)
                {
                    //fncSNDeleteBuddy(uName);
                    fncSNInsertBuddy(uName, "Offline");
                    fncSNDeleteNode(uName);
                    fncUpdateUserBuddyStatus(uName, "Offline");
                }
                OpenConnection();
                // End Meet Code.
                if (!IsSuperNode && uName != "")
                {
                    //	System.Windows.Forms.MessageBox.Show("1");					

                    sqlcmd = new SqlCeCommand("Select SuperNode_Id from SuperNode_Node_Info where Node_Name='" + uName + "'");
                    sqlcmd.Connection = LocalSQLConn;
                    object objsvcUnJoinSuperNode_Node_Info = sqlcmd.ExecuteScalar();
                    //System.Windows.Forms.MessageBox.Show("2");

                    sqlcmd = new SqlCeCommand("Select NodeCount from SuperNode_Info where Id='" + objsvcUnJoinSuperNode_Node_Info.ToString() + "'");
                    sqlcmd.Connection = LocalSQLConn;
                    object objsvcUnJoinNodeCount = sqlcmd.ExecuteScalar();
                    if (objsvcUnJoinNodeCount != null && int.Parse(objsvcUnJoinNodeCount.ToString()) > 0)
                    {
                        //	System.Windows.Forms.MessageBox.Show("3");

                        int intDecrementCounter = int.Parse(objsvcUnJoinNodeCount.ToString()) - 1;
                        sqlcmd = new SqlCeCommand("UPDATE SuperNode_Info set NodeCount='" + intDecrementCounter + "' Where Id='" + objsvcUnJoinSuperNode_Node_Info.ToString() + "'");
                        sqlcmd.Connection = LocalSQLConn;
                        sqlcmd.ExecuteNonQuery();
                        //	System.Windows.Forms.MessageBox.Show("4");
                    }
                    sqlcmd = new SqlCeCommand("Delete from SuperNode_Node_Info where Node_Name='" + uName + "'");
                    sqlcmd.Connection = LocalSQLConn;
                    sqlcmd.ExecuteNonQuery();
                    //	System.Windows.Forms.MessageBox.Show("5");
                }
                else
                {
                    sqlcmd = new SqlCeCommand("Delete from SuperNode_Info where SuperNodeName='" + uName + "'");
                    sqlcmd.Connection = LocalSQLConn;
                    sqlcmd.ExecuteNonQuery();
                    //	System.Windows.Forms.MessageBox.Show("6");
                    //Remove from SuperNode_Info
                }

                // **
                if (lstsSuperNodeInfo.Contains(IP))
                {
                    lstsSuperNodeInfo.Remove(IP);
                }
                else if (lstsSuperNodeInfo.Contains(uName))
                {
                    lstsSuperNodeInfo.Remove(uName);
                }
                //  Conn.Close();
                //  Conn.Dispose();

            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex.Message);
                //System.Windows.Forms.MessageBox.Show(ex.Message);
                ex.Data.Add("My Key", "BootstrapServiceDomain_EntHttpBSUnJoin()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
                //  Conn.Close();
                //  Conn.Dispose();
            }

        }

        //VMukti.Business.WCFServices.SuperNodeServices.DataContract.clsSuperNodeDataContract BootstrapServiceDomain_EntHttpBsGetSuperNodeIP(string uName, string IP, bool blSuperNode)
        //{
        //    //  SqlCeConnection Conn = new SqlCeConnection(awClientConnectionString);
        //    DataTable dt = new DataTable();
        //    SqlCeCommand sqlcmd = null;

        //    try
        //    {
        //        // Meet Code For Buddylist Implementation.
        //        if (uName != null && uName != string.Empty)
        //        {
        //            fncSNInsertBuddy(uName, "Online");
        //            fncSNInsertNode(uName);
        //            fncUpdateUserBuddyStatus(uName, "Online");
        //        }
        //        // End Meet Code.
        //        //  Conn.Open();
        //        clsSuperNodeDataContract objSuperNodeInfo = new clsSuperNodeDataContract();
        //        OpenConnection();
        //        if (!blSuperNode) //Find Free SuperNode from the list and allocate itto Node
        //        {
        //            //Find Free available SuperNode
        //            sqlcmd = new SqlCeCommand("SELECT count(*) FROM SuperNode_Info");
        //            sqlcmd.Connection = LocalSQLConn;
        //            object objSuperNodeCount = sqlcmd.ExecuteScalar();

        //            SqlCeDataAdapter sqlDataAdap = null;
        //            if (int.Parse(objSuperNodeCount.ToString()) > 1)
        //            {
        //                sqlDataAdap = new SqlCeDataAdapter("SELECT * FROM SuperNode_Info WHERE SuperNodeIP <> '" + strCurrentMachineIP + "' ORDER BY NodeCount", LocalSQLConn);
        //                sqlDataAdap.Fill(dt);
        //                objSuperNodeInfo.SuperNodeIP = dt.Rows[0]["SuperNodeIP"].ToString();
        //            }
        //            else
        //            {
        //                sqlDataAdap = new SqlCeDataAdapter("SELECT * FROM SuperNode_Info ORDER BY NodeCount", LocalSQLConn);
        //                sqlDataAdap.Fill(dt);
        //                objSuperNodeInfo.SuperNodeIP = dt.Rows[0]["SuperNodeIP"].ToString();
        //            }
        //            int intIncrementCounter = int.Parse(dt.Rows[0]["NodeCount"].ToString()) + 1;
        //            sqlcmd = new SqlCeCommand("Update SuperNode_Info Set NodeCount = '" + intIncrementCounter + "' where Id='" + dt.Rows[0]["Id"].ToString() + "'");
        //            sqlcmd.Connection = LocalSQLConn;
        //            sqlcmd.ExecuteNonQuery();

        //            sqlcmd = new SqlCeCommand("Select Id from SuperNode_Node_Info where Node_Name = '" + uName + "'");
        //            sqlcmd.Connection = LocalSQLConn;
        //            object objTemp = sqlcmd.ExecuteScalar();
        //            if (objTemp != null)
        //            {
        //                sqlcmd = new SqlCeCommand("Update SuperNode_Node_Info set SuperNode_Id='" + dt.Rows[0]["Id"].ToString() + "' where Node_Name='" + uName + "'");
        //                sqlcmd.Connection = LocalSQLConn;
        //                sqlcmd.ExecuteNonQuery();
        //            }
        //            else
        //            {
        //                sqlcmd = new SqlCeCommand("INSERT INTO SuperNode_Node_Info (SuperNode_Id,Node_Name) VALUES ('" + dt.Rows[0]["Id"].ToString() + "','" + uName + "')");
        //                sqlcmd.Connection = LocalSQLConn;
        //                sqlcmd.ExecuteNonQuery();
        //            }
        //            dt.Clear();
        //        }
        //        else //Add New SuperNode to available superNode List
        //        {
        //            sqlcmd = new SqlCeCommand("SELECT Count(*) from SuperNode_Info where SuperNodeIP = '" + IP + "'");
        //            sqlcmd.Connection = LocalSQLConn;
        //            object temp = sqlcmd.ExecuteScalar();
        //            if (int.Parse(temp.ToString()) <= 0)
        //            {
        //                sqlcmd = new SqlCeCommand("INSERT INTO SuperNode_Info (SuperNodeIP, NodeCount,SuperNodeName) VALUES ('" + IP + "', '0','" + uName + "')");
        //                sqlcmd.Connection = LocalSQLConn;
        //                sqlcmd.ExecuteNonQuery();
        //            }
        //            objSuperNodeInfo.SuperNodeIP = IP;
        //        }

        //        // Meet Code For Buddylist Implementation.

        //        if (VMuktiAPI.VMuktiInfo.CurrentPeer.CurrAuthType == AuthType.SIPAuthentication)
        //        {
        //            objSuperNodeInfo.FileExists = false;
        //            sqlcmd = new SqlCeCommand("SELECT SIP_Number FROM SIP_Info WHERE UserName='" + uName + "'");
        //            sqlcmd.Connection = LocalSQLConn;
        //            object objTempSipNumber = sqlcmd.ExecuteScalar();

        //            sqlcmd = new SqlCeCommand("INSERT INTO Registered_Users (UserName,SIPNumber) VALUES ('" + uName + "','" + objTempSipNumber.ToString() + "')");
        //            sqlcmd.Connection = LocalSQLConn;
        //            sqlcmd.ExecuteNonQuery();
        //        }
        //        //  Conn.Close();
        //        //  Conn.Dispose();
        //        return objSuperNodeInfo;
        //    }
        //    catch (Exception ex)
        //    {
        //        //Console.WriteLine(ex.Message);
        //        ex.Data.Add("My Key", "BootstrapServiceDomain_EntHttpBsGetSuperNodeIP()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
        //        ClsException.LogError(ex);
        //        ClsException.WriteToErrorLogFile(ex);
        //        //   Conn.Close();
        //        //   Conn.Dispose();
        //        return null;
        //    }
        //}

        VMukti.Business.WCFServices.SuperNodeServices.DataContract.clsSuperNodeDataContract BootstrapServiceDomain_EntHttpBsGetSuperNodeIP(string uName, string IP, bool blSuperNode)
        {
           // SqlCeConnection Conn = new SqlCeConnection(awClientConnectionString);

            SqlCeCommand sqlcmd = null;

            try
            {
                // Meet Code For Buddylist Implementation.
                if (uName != null && uName != string.Empty)
                {
                    fncSNInsertBuddy(uName, "Online");
                    fncSNInsertNode(uName);
                    fncUpdateUserBuddyStatus(uName, "Online");
                }
                // End Meet Code.

                clsSuperNodeDataContract objSuperNodeInfo = new clsSuperNodeDataContract();

                //super node checking
                #region shilpa code
                if (!blSuperNode) //Find Free SuperNode from the list and allocate itto Node
                {
                    //Find Free available SuperNode
                    //sqlcmd = new SqlCeCommand("SELECT count(*) FROM SuperNode_Info");
                    //sqlcmd.Connection = Conn;
                    //object objSuperNodeCount = sqlcmd.ExecuteScalar();

                    //shilpa code 5-Feb-2008
                    //code for super node service availabity checking 
                    //if super node is still available than findAvailableIp=true

                    Boolean isSuperNodeAvailable = false;
                    int intIncrementCounter = 0;
                    String SupId = null;
                    //Find Free available SuperNode untill can not be found
                    while (isSuperNodeAvailable == false)
                    {
                        //Find Free available SuperNode
                        SqlCeDataAdapter sqlDataAdap = null;
                        DataTable dt = null;
                       // Conn.Open();
                        OpenConnection();
                        sqlcmd = new SqlCeCommand("SELECT count(*) FROM SuperNode_Info");
                        sqlcmd.Connection = LocalSQLConn;
                        object objSuperNodeCount = sqlcmd.ExecuteScalar();
                        sqlDataAdap = null;

                        //End shilpa code 5-Feb-2008

                        if (int.Parse(objSuperNodeCount.ToString()) > 1)
                        {
                            sqlDataAdap = new SqlCeDataAdapter("SELECT * FROM SuperNode_Info WHERE SuperNodeIP <> '" + strCurrentMachineIP + "' ORDER BY NodeCount", LocalSQLConn);
                            dt = new DataTable();
                            sqlDataAdap.Fill(dt);
                            objSuperNodeInfo.SuperNodeIP = dt.Rows[0]["SuperNodeIP"].ToString();
                            isSuperNodeAvailable = checkSuperNodeAvailable(objSuperNodeInfo.SuperNodeIP);
                        }
                        else
                        {
                            sqlDataAdap = new SqlCeDataAdapter("SELECT * FROM SuperNode_Info ORDER BY NodeCount", LocalSQLConn);
                            dt = new DataTable();
                            sqlDataAdap.Fill(dt);
                            objSuperNodeInfo.SuperNodeIP = dt.Rows[0]["SuperNodeIP"].ToString();

                            //shilpa 5-Feb-2008
                            //isSuperNodeAvailable = true because we are assigning  boostrap as super node
                            //which will be running continuesly
                            isSuperNodeAvailable = true;
                        }

                        //shilpa code 5-Feb-2008
                        //method for super node service checking

                        if (!isSuperNodeAvailable)
                        {
                            //assign all its  node to the another super node 
                            //shilpa code
                            //6-Feb-2008

                            //deleting the super node entry
                            adjustSuperNode(objSuperNodeInfo.SuperNodeIP);
                        }
                        else
                        {
                            //continue
                            //with the same super node ip
                            //exit from the while loop
                            intIncrementCounter = int.Parse(dt.Rows[0]["NodeCount"].ToString()) + 1;
                            SupId = dt.Rows[0]["Id"].ToString();
                        }
                        dt.Clear();
                        dt.Reset();
                      //  Conn.Close();

                    } // end while

                #endregion

                    // end code
                    // shilpa 5-Feb-2008
                  //  Conn.Open();
                    //int intIncrementCounter = int.Parse(dt.Rows[0]["NodeCount"].ToString()) + 1;
                    OpenConnection();
                    sqlcmd = new SqlCeCommand("Update SuperNode_Info Set NodeCount = '" + intIncrementCounter + "' where Id='" + SupId + "'");
                    sqlcmd.Connection = LocalSQLConn;
                    int TotUpdate = sqlcmd.ExecuteNonQuery();

                    sqlcmd = new SqlCeCommand("Select Id from SuperNode_Node_Info where Node_Name = '" + uName + "'");
                    sqlcmd.Connection = LocalSQLConn;
                    object objTemp = sqlcmd.ExecuteScalar();
                    if (objTemp != null)
                    {
                        sqlcmd = new SqlCeCommand("Update SuperNode_Node_Info set SuperNode_Id='" + SupId + "' where Node_Name='" + uName + "'");
                        sqlcmd.Connection = LocalSQLConn;
                        sqlcmd.ExecuteNonQuery();
                    }
                    else
                    {
                        sqlcmd = new SqlCeCommand("INSERT INTO SuperNode_Node_Info (SuperNode_Id,Node_Name) VALUES ('" + SupId + "','" + uName + "')");
                        sqlcmd.Connection = LocalSQLConn;
                        sqlcmd.ExecuteNonQuery();
                    }
                    //Conn.Close();

                }
                else //Add New SuperNode to available superNode List
                {
                   // Conn.Open();
                    OpenConnection();
                    sqlcmd = new SqlCeCommand("SELECT Count(*) from SuperNode_Info where SuperNodeIP = '" + IP + "'");
                    sqlcmd.Connection = LocalSQLConn;
                    object temp = sqlcmd.ExecuteScalar();
                    if (int.Parse(temp.ToString()) <= 0)
                    {
                        sqlcmd = new SqlCeCommand("INSERT INTO SuperNode_Info (SuperNodeIP, NodeCount,SuperNodeName) VALUES ('" + IP + "', '0','" + uName + "')");
                        sqlcmd.Connection = LocalSQLConn;
                        sqlcmd.ExecuteNonQuery();
                    }
                    objSuperNodeInfo.SuperNodeIP = IP;
                    // **
                    if (!lstsSuperNodeInfo.Contains(IP))
                    {
                        lstsSuperNodeInfo.Add(IP);
                    }

                   // Conn.Close();
                }

                // Meet Code For Buddylist Implementation.


                if (VMuktiAPI.VMuktiInfo.CurrentPeer.CurrAuthType == AuthType.SIPAuthentication)
                {
                    objSuperNodeInfo.FileExists = false;
                    sqlcmd = new SqlCeCommand("SELECT SIP_Number FROM SIP_Info WHERE UserName='" + uName + "'");
                    sqlcmd.Connection = LocalSQLConn;
                    object objTempSipNumber = sqlcmd.ExecuteScalar();

                    sqlcmd = new SqlCeCommand("INSERT INTO Registered_Users (UserName,SIPNumber) VALUES ('" + uName + "','" + objTempSipNumber.ToString() + "')");
                    sqlcmd.Connection = LocalSQLConn;
                    sqlcmd.ExecuteNonQuery();
                }
            //    Conn.Close();
              //  Conn.Dispose();
                return objSuperNodeInfo;
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex.Message);
                ex.Data.Add("My Key", "BootstrapServiceDomain_EntHttpBsGetSuperNodeIP()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
             //   Conn.Close();
             //   Conn.Dispose();
                return null;
            }
        }

        string BootstrapServiceDomain_EntHttpAddBuddy(string uName, string BuddyName)
        {

            //   SqlCeConnection Conn = new SqlCeConnection(ClientConnectionString);
            //   Conn.Open();
            try
            {
                OpenConnection();
                SqlCeCommand sqlcmd = new SqlCeCommand("SELECT Count(*) FROM Node_Status  where Buddy_Name='" + BuddyName + "'", LocalSQLConn);
                object objsqlAddUser = sqlcmd.ExecuteScalar();
                if (int.Parse(objsqlAddUser.ToString()) > 0)
                {
                    //SqlCeConnection conn = new SqlCeConnection(ClientConnectionString);
                    //conn.Open();
                    SqlCeDataAdapter dataAdapter = new SqlCeDataAdapter("SELECT * FROM Node_Status where Buddy_Name='" + BuddyName + "'", LocalSQLConn);
                    DataTable dataTable = new DataTable();
                    dataAdapter.Fill(dataTable);
                    //     Conn.Close();
                    //     Conn.Dispose();
                    fncUpdateBuddyStatus(uName, BuddyName, dataTable.Rows[0][2].ToString());
                    fncUpdateBuddyStatus(BuddyName, uName, "Online");
                    return dataTable.Rows[0][1].ToString() + "-" + dataTable.Rows[0][2].ToString();
                }
                else
                {

                    //Conn.Close();
                    //      Conn.Dispose();
                    return string.Empty;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error In Inserting Value from NodeStatus table on SuperNdoeMachine");
                ex.Data.Add("My Key", "fncSNInsertBuddy()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
                //   Conn.Close();
                //   Conn.Dispose();
                return string.Empty;
            }
        }

        void BootstrapServiceDomain_EntHttpRemoveBuddy(string uName, string BuddyName)
        {
            //   SqlCeConnection Conn = new SqlCeConnection(ClientConnectionString);
            //   Conn.Open();
            try
            {
                SqlCeCommand sqlcmd = new SqlCeCommand("delete from User_BuddyList where UserName='" + uName + "' and BuddyName='" + BuddyName + "'", LocalSQLConn);
                sqlcmd.ExecuteNonQuery();
                //      Conn.Close();
                //     Conn.Dispose();
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "BootstrapServiceDomain_EntHttpRemoveBuddy()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
                //       Conn.Close();
                //      Conn.Dispose();
            }
        }

        void BootstrapServiceDomain_EntHttpBSAuthorizedUser(string uName, string IP, bool blSuperNode)
        {
            SqlCeCommand sqlcmd = null;
            //  SqlCeConnection Conn = new SqlCeConnection(awClientConnectionString);
            try
            {
                if (uName != null && uName != string.Empty)
                {
                    fncSNInsertBuddy(uName, "Online");
                    fncSNInsertNode(uName);
                    fncUpdateUserBuddyStatus(uName, "Online");
                }
                OpenConnection();
                //   Conn.Open();
                if (blSuperNode)
                {
                    sqlcmd = new SqlCeCommand("Update SuperNode_Info Set SuperNodeName = '" + uName + "' where SuperNodeName='" + IP + "'");
                    sqlcmd.Connection = LocalSQLConn;
                    sqlcmd.ExecuteNonQuery();
                }
                else
                {
                    sqlcmd = new SqlCeCommand("Update SuperNode_Node_Info Set Node_Name = '" + uName + "' where Node_Name='" + IP + "'");
                    sqlcmd.Connection = LocalSQLConn;
                    sqlcmd.ExecuteNonQuery();
                }
                if (blSuperNode)
                {
                    for (int i = 0; i < lstsSuperNodeInfo.Count; i++)
                    {
                        if (lstsSuperNodeInfo[i] == IP)
                        {
                            lstsSuperNodeInfo[i] = uName;
                            break;
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "BootstrapServiceDomain_EntHttpBSAuthorizedUser()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        #endregion

        // Meet Code For Buddylist Implementation.
        #region DataBase Creation Function
       // public static string ClientConnectionString = @"Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "AllocateConferenceNumber.sdf";
        

        public void fncCreateBuddyStatusTable()
        {
            try
            {

              //  ClientConnectionString = @"Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "AllocateConferenceNumber.sdf";
              //  strLocalDBPath = AppDomain.CurrentDomain.BaseDirectory + "AllocateConferenceNumber.sdf";


                if (false == File.Exists(strLocalDBPath))
                {
                    SqlCeEngine clientEngine = new SqlCeEngine(ClientConnectionString);
                    clientEngine.CreateDatabase();
                }
                if (!IsTableExits("Node_Status"))
                {
                    SqlCeClientSyncProvider sync = new SqlCeClientSyncProvider(ClientConnectionString);

                    SyncTable tblNode_Status = new SyncTable("Node_Status");

                    SyncSchema syncSchemaLead = new SyncSchema();
                    syncSchemaLead.Tables.Add("Node_Status");
                    syncSchemaLead.Tables["Node_Status"].Columns.Add("Buddy_ID");
                    syncSchemaLead.Tables["Node_Status"].Columns["Buddy_ID"].ProviderDataType = SqlDbType.BigInt.ToString();
                    syncSchemaLead.Tables["Node_Status"].Columns["Buddy_ID"].AutoIncrement = true;
                    syncSchemaLead.Tables["Node_Status"].Columns["Buddy_ID"].AutoIncrementSeed = 1;
                    syncSchemaLead.Tables["Node_Status"].Columns["Buddy_ID"].AutoIncrementStep = 1;
                    syncSchemaLead.Tables["Node_Status"].PrimaryKey = new string[] { "Buddy_ID" };

                    syncSchemaLead.Tables["Node_Status"].Columns.Add("Buddy_Name");
                    syncSchemaLead.Tables["Node_Status"].Columns["Buddy_Name"].ProviderDataType = SqlDbType.NVarChar.ToString();
                    syncSchemaLead.Tables["Node_Status"].Columns["Buddy_Name"].MaxLength = 30;

                    syncSchemaLead.Tables["Node_Status"].Columns.Add("Buddy_Status");
                    syncSchemaLead.Tables["Node_Status"].Columns["Buddy_Status"].ProviderDataType = SqlDbType.NVarChar.ToString();
                    syncSchemaLead.Tables["Node_Status"].Columns["Buddy_Status"].MaxLength = 30;

                    sync.CreateSchema(tblNode_Status, syncSchemaLead);
                }
                if (VMuktiInfo.CurrentPeer.DisplayName != null && VMuktiInfo.CurrentPeer.DisplayName != string.Empty)
                {
                    fncSNInsertBuddy(VMuktiInfo.CurrentPeer.DisplayName, "Online");
                }
            }
            catch (Exception ex)
            {
                // MessageBox.Show("Error In Creating Node_Status Table");
                ex.Data.Add("My Key", "fncCreateBuddyStatusTable()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        public void fncCreateSNNodeInfoTable()
        {
            try
            {
               // ClientConnectionString = @"Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "AllocateConferenceNumber.sdf";
              //  strLocalDBPath = AppDomain.CurrentDomain.BaseDirectory + "AllocateConferenceNumber.sdf";

                if (false == File.Exists(strLocalDBPath))
                {
                    SqlCeEngine clientEngine = new SqlCeEngine(ClientConnectionString);
                    clientEngine.CreateDatabase();
                }
                if (!IsTableExits("Node_Info"))
                {
                    SqlCeClientSyncProvider sync = new SqlCeClientSyncProvider(ClientConnectionString);

                    SyncTable tblNode_Info = new SyncTable("Node_Info");

                    SyncSchema syncSchemaLead = new SyncSchema();
                    syncSchemaLead.Tables.Add("Node_Info");
                    syncSchemaLead.Tables["Node_Info"].Columns.Add("Node_ID");
                    syncSchemaLead.Tables["Node_Info"].Columns["Node_ID"].ProviderDataType = SqlDbType.BigInt.ToString();
                    syncSchemaLead.Tables["Node_Info"].Columns["Node_ID"].AutoIncrement = true;
                    syncSchemaLead.Tables["Node_Info"].Columns["Node_ID"].AutoIncrementSeed = 1;
                    syncSchemaLead.Tables["Node_Info"].Columns["Node_ID"].AutoIncrementStep = 1;
                    syncSchemaLead.Tables["Node_Info"].PrimaryKey = new string[] { "Node_ID" };

                    syncSchemaLead.Tables["Node_Info"].Columns.Add("Node_Name");
                    syncSchemaLead.Tables["Node_Info"].Columns["Node_Name"].ProviderDataType = SqlDbType.NVarChar.ToString();
                    syncSchemaLead.Tables["Node_Info"].Columns["Node_Name"].MaxLength = 30;

                    sync.CreateSchema(tblNode_Info, syncSchemaLead);
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Error In Creating Node_Info Table");
                ex.Data.Add("My Key", "fncCreateSNNodeInfoTable()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        public void fncCreateUserBuddyListTable()
        {
            try
            {
             //   ClientConnectionString = @"Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "AllocateConferenceNumber.sdf";
             //   strLocalDBPath = AppDomain.CurrentDomain.BaseDirectory + "AllocateConferenceNumber.sdf";

                if (false == File.Exists(strLocalDBPath))
                {
                    SqlCeEngine clientEngine = new SqlCeEngine(ClientConnectionString);
                    clientEngine.CreateDatabase();
                }
                if (!IsTableExits("User_BuddyList"))
                {
                    SqlCeClientSyncProvider sync = new SqlCeClientSyncProvider(ClientConnectionString);

                    SyncTable tblUser_BuddyList = new SyncTable("User_BuddyList");

                    SyncSchema syncSchemaLead = new SyncSchema();
                    syncSchemaLead.Tables.Add("User_BuddyList");
                    syncSchemaLead.Tables["User_BuddyList"].Columns.Add("ID");
                    syncSchemaLead.Tables["User_BuddyList"].Columns["ID"].ProviderDataType = SqlDbType.BigInt.ToString();
                    syncSchemaLead.Tables["User_BuddyList"].Columns["ID"].AutoIncrement = true;
                    syncSchemaLead.Tables["User_BuddyList"].Columns["ID"].AutoIncrementSeed = 1;
                    syncSchemaLead.Tables["User_BuddyList"].Columns["ID"].AutoIncrementStep = 1;
                    syncSchemaLead.Tables["User_BuddyList"].PrimaryKey = new string[] { "ID" };

                    syncSchemaLead.Tables["User_BuddyList"].Columns.Add("UserName");
                    syncSchemaLead.Tables["User_BuddyList"].Columns["UserName"].ProviderDataType = SqlDbType.NVarChar.ToString();
                    syncSchemaLead.Tables["User_BuddyList"].Columns["UserName"].MaxLength = 30;
                    syncSchemaLead.Tables["User_BuddyList"].Columns["UserName"].AllowNull = false;


                    syncSchemaLead.Tables["User_BuddyList"].Columns.Add("BuddyName");
                    syncSchemaLead.Tables["User_BuddyList"].Columns["BuddyName"].ProviderDataType = SqlDbType.NVarChar.ToString();
                    syncSchemaLead.Tables["User_BuddyList"].Columns["BuddyName"].MaxLength = 30;
                    syncSchemaLead.Tables["User_BuddyList"].Columns["BuddyName"].AllowNull = false;

                    syncSchemaLead.Tables["User_BuddyList"].Columns.Add("BuddyStatus");
                    syncSchemaLead.Tables["User_BuddyList"].Columns["BuddyStatus"].ProviderDataType = SqlDbType.NVarChar.ToString();
                    syncSchemaLead.Tables["User_BuddyList"].Columns["BuddyStatus"].MaxLength = 20;
                    syncSchemaLead.Tables["User_BuddyList"].Columns["BuddyStatus"].AllowNull = false;


                    sync.CreateSchema(tblUser_BuddyList, syncSchemaLead);
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Error In Creating Node_Info Table");
                ex.Data.Add("My Key", "fncCreateSNNodeInfoTable()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        public void fncCreateUserSuperNodeInfoTable()
        {
            try
            {
            //    ClientConnectionString = @"Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "AllocateConferenceNumber.sdf";
            //    strLocalDBPath = AppDomain.CurrentDomain.BaseDirectory + "AllocateConferenceNumber.sdf";

                if (false == File.Exists(strLocalDBPath))
                {
                    SqlCeEngine clientEngine = new SqlCeEngine(ClientConnectionString);
                    clientEngine.CreateDatabase();
                }
                if (!IsTableExits("SuperNode_Info"))
                {
                    SqlCeClientSyncProvider sync = new SqlCeClientSyncProvider(ClientConnectionString);

                    SyncTable tblSuperNodeInfo = new SyncTable("SuperNode_Info");

                    SyncSchema syncSchemaLead = new SyncSchema();
                    syncSchemaLead.Tables.Add("SuperNode_Info");
                    syncSchemaLead.Tables["SuperNode_Info"].Columns.Add("ID");
                    syncSchemaLead.Tables["SuperNode_Info"].Columns["ID"].ProviderDataType = SqlDbType.Int.ToString();
                    syncSchemaLead.Tables["SuperNode_Info"].Columns["ID"].AutoIncrement = true;
                    syncSchemaLead.Tables["SuperNode_Info"].Columns["ID"].AutoIncrementSeed = 1;
                    syncSchemaLead.Tables["SuperNode_Info"].Columns["ID"].AutoIncrementStep = 1;
                    syncSchemaLead.Tables["SuperNode_Info"].PrimaryKey = new string[] { "ID" };

                    syncSchemaLead.Tables["SuperNode_Info"].Columns.Add("SuperNodeIP");
                    syncSchemaLead.Tables["SuperNode_Info"].Columns["SuperNodeIP"].ProviderDataType = SqlDbType.NVarChar.ToString();
                    syncSchemaLead.Tables["SuperNode_Info"].Columns["SuperNodeIP"].MaxLength = 30;
                    syncSchemaLead.Tables["SuperNode_Info"].Columns["SuperNodeIP"].AllowNull = false;


                    syncSchemaLead.Tables["SuperNode_Info"].Columns.Add("NodeCount");
                    syncSchemaLead.Tables["SuperNode_Info"].Columns["NodeCount"].ProviderDataType = SqlDbType.Int.ToString();
                    //syncSchemaLead.Tables["SuperNode_Info"].Columns["NodeCount"].MaxLength = 4;


                    syncSchemaLead.Tables["SuperNode_Info"].Columns.Add("SuperNodeName");
                    syncSchemaLead.Tables["SuperNode_Info"].Columns["SuperNodeName"].ProviderDataType = SqlDbType.NVarChar.ToString();
                    syncSchemaLead.Tables["SuperNode_Info"].Columns["SuperNodeName"].MaxLength = 50;
                    syncSchemaLead.Tables["SuperNode_Info"].Columns["SuperNodeName"].AllowNull = false;


                    sync.CreateSchema(tblSuperNodeInfo, syncSchemaLead);
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Error In Creating Node_Info Table");
                ex.Data.Add("My Key", "fncCreateSNNodeInfoTable()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        public void fncCreateUserSuperNode_NodeInfoTable()
        {
            try
            {
             //   ClientConnectionString = @"Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "AllocateConferenceNumber.sdf";
              //  strLocalDBPath = AppDomain.CurrentDomain.BaseDirectory + "AllocateConferenceNumber.sdf";

                if (false == File.Exists(strLocalDBPath))
                {
                    SqlCeEngine clientEngine = new SqlCeEngine(ClientConnectionString);
                    clientEngine.CreateDatabase();
                }
                if (!IsTableExits("SuperNode_Node_Info"))
                {
                    SqlCeClientSyncProvider sync = new SqlCeClientSyncProvider(ClientConnectionString);

                    SyncTable tblSuperNode_Node_Info = new SyncTable("SuperNode_Node_Info");

                    SyncSchema syncSchemaLead = new SyncSchema();
                    syncSchemaLead.Tables.Add("SuperNode_Node_Info");
                    syncSchemaLead.Tables["SuperNode_Node_Info"].Columns.Add("ID");
                    syncSchemaLead.Tables["SuperNode_Node_Info"].Columns["ID"].ProviderDataType = SqlDbType.Int.ToString();
                    syncSchemaLead.Tables["SuperNode_Node_Info"].Columns["ID"].AutoIncrement = true;
                    syncSchemaLead.Tables["SuperNode_Node_Info"].Columns["ID"].AutoIncrementSeed = 1;
                    syncSchemaLead.Tables["SuperNode_Node_Info"].Columns["ID"].AutoIncrementStep = 1;
                    syncSchemaLead.Tables["SuperNode_Node_Info"].PrimaryKey = new string[] { "ID" };

                    syncSchemaLead.Tables["SuperNode_Node_Info"].Columns.Add("SuperNode_Id");
                    syncSchemaLead.Tables["SuperNode_Node_Info"].Columns["SuperNode_Id"].ProviderDataType = SqlDbType.NVarChar.ToString();
                    syncSchemaLead.Tables["SuperNode_Node_Info"].Columns["SuperNode_Id"].MaxLength = 30;
                    syncSchemaLead.Tables["SuperNode_Node_Info"].Columns["SuperNode_Id"].AllowNull = false;


                    syncSchemaLead.Tables["SuperNode_Node_Info"].Columns.Add("Node_Name");
                    syncSchemaLead.Tables["SuperNode_Node_Info"].Columns["Node_Name"].ProviderDataType = SqlDbType.NVarChar.ToString();
                    syncSchemaLead.Tables["SuperNode_Node_Info"].Columns["Node_Name"].MaxLength = 50;
                    syncSchemaLead.Tables["SuperNode_Node_Info"].Columns["Node_Name"].AllowNull = false;


                    sync.CreateSchema(tblSuperNode_Node_Info, syncSchemaLead);
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Error In Creating Node_Info Table");
                ex.Data.Add("My Key", "fncCreateSNNodeInfoTable()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        public bool IsTableExits(string strTableName)
        {
         //   SqlCeConnection ce = new SqlCeConnection(ClientConnectionString);
            try
            {
            //    ce.Open();
                string str = "SELECT COUNT(*) FROM Information_Schema.Tables WHERE (TABLE_NAME ='" + strTableName + "')";
                OpenConnection();
                SqlCeCommand cmd = new SqlCeCommand(str, LocalSQLConn);
                object i = cmd.ExecuteScalar();
          //      ce.Close();
          //      ce.Dispose();
                if (int.Parse(i.ToString()) > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }


            }
            catch (Exception ex)
            {
                // MessageBox.Show("Exception In Table Checking Table Status");
                ex.Data.Add("My Key", "IsTableExits()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
        //        ce.Close();
        //        ce.Dispose();
                return false;
            }
        }




        private bool IsRecordExists(string strBuddyName, string strTableName, string strPrimaryKey)
        {
          //  SqlCeConnection ce = null;
            try
            {
            //    ce = new SqlCeConnection(ClientConnectionString);
            //    ce.Open();
                string str = "SELECT COUNT(*) FROM " + strTableName + " WHERE (" + strPrimaryKey + " ='" + strBuddyName + "')";
                //string str = "Select Count(*) From Loginserver_Master";
                OpenConnection();
                SqlCeCommand cmd = new SqlCeCommand(str, LocalSQLConn);

                object i = cmd.ExecuteScalar();
            //    ce.Close();
            //    ce.Dispose();
                if (int.Parse(i.ToString()) > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Exception In Checking Record Exist");
                ex.Data.Add("My Key", "IsRecordExists()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
          //      ce.Close();
          //      ce.Dispose();
                return false;
            }

        }

        public void fncSNInsertBuddy(string strBuddyName, string strBuddyStatus)
        {
       //     SqlCeConnection ceConn = new SqlCeConnection(ClientConnectionString);
            try
            {
                if (!IsRecordExists(strBuddyName, "Node_Status", "Buddy_Name"))
                {
                //    ceConn.Open();
                    OpenConnection();
                    string str = "insert into Node_Status(Buddy_Name,Buddy_Status) values(@Buddy_Name,@Buddy_Status) ";
                    SqlCeCommand cmd = new SqlCeCommand(str);
                    cmd.Connection = LocalSQLConn;

                    cmd.Parameters.AddWithValue("@Buddy_Name", strBuddyName);
                    cmd.Parameters.AddWithValue("@Buddy_Status", strBuddyStatus);
                    cmd.ExecuteNonQuery();
               //     ceConn.Close();
               //     ceConn.Dispose();
                }
                else
                {
                    //  string str = "Update Node_Status Set Buddy_Status=" + strBuddyStatus + " Where Buddy_Name=" + strBuddyName;
                //    ceConn.Open();
                    OpenConnection();
                    string str = "Update Node_Status Set Buddy_Status='" + strBuddyStatus + "' Where Buddy_Name='" + strBuddyName + "'";
                    SqlCeCommand cmd = new SqlCeCommand(str);
                    cmd.Connection = LocalSQLConn;
                    cmd.ExecuteNonQuery();
               //     ceConn.Close();
               //     ceConn.Dispose();
                }
                //MessageBox.Show("Buddy " + strBuddyName + " is " + strBuddyStatus,"Boot Strap Domain");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error In Inserting Value from NodeStatus table on SuperNdoeMachine");
                ex.Data.Add("My Key", "fncSNInsertBuddy()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
             //   ceConn.Close();
              //  ceConn.Dispose();
            }
        }

        private void fncSNDeleteBuddy(string strBuddyName)
        {
          //  SqlCeConnection ceConn = new SqlCeConnection(ClientConnectionString);
            try
            {
                if (IsRecordExists(strBuddyName, "Node_Status", "Buddy_Name"))
                {
                //    ceConn.Open();
                    OpenConnection();
                    string str = "delete from Node_Status where Buddy_Name = @Buddy_Name";
                    SqlCeCommand cmd = new SqlCeCommand(str);
                    cmd.Connection = LocalSQLConn;

                    cmd.Parameters.AddWithValue("@Buddy_Name", strBuddyName);
                    cmd.ExecuteNonQuery();
              //      ceConn.Close();
              //      ceConn.Dispose();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error In Deleteing Value from NodeStatus table on SuperNdoeMachine.");
                ex.Data.Add("My Key", "fncSNDeleteBuddy()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
             //   ceConn.Close();
             //   ceConn.Dispose();
            }
        }

        private void fncSNInsertNode(string uName)
        {
         //   SqlCeConnection ceConn = new SqlCeConnection(ClientConnectionString);
            try
            {
                if (!IsRecordExists(uName, "Node_Info", "Node_Name"))
                {
                //    ceConn.Open();
                    OpenConnection();
                    string str = "insert into Node_Info(Node_Name) values(@Node_Name) ";
                    SqlCeCommand cmd = new SqlCeCommand(str);
                    cmd.Connection = LocalSQLConn;

                    cmd.Parameters.AddWithValue("@Node_Name", uName);
                    cmd.ExecuteNonQuery();
              //      ceConn.Close();
               //     ceConn.Dispose();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error In Inserting Value from NodeInfo table on SuperNdoeMachine");
                ex.Data.Add("My Key", "fncSNInsertNode()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
           //     ceConn.Close();
            //    ceConn.Dispose();
            }
        }

        private void fncSNDeleteNode(string uName)
        {
          //  SqlCeConnection ceConn = new SqlCeConnection(ClientConnectionString);
            try
            {
                if (IsRecordExists(uName, "Node_Info", "Node_Name"))
                {
               //     ceConn.Open();
                    OpenConnection();
                    string str = "delete from Node_Info where Node_Name = @Node_Name";
                    SqlCeCommand cmd = new SqlCeCommand(str);
                    cmd.Connection = LocalSQLConn;

                    cmd.Parameters.AddWithValue("@Node_Name", uName);
                    cmd.ExecuteNonQuery();
               //     ceConn.Close();
               //     ceConn.Dispose();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error In Deleteing Value from NodeInfo table on SuperNdoeMachine.");
                ex.Data.Add("My Key", "fncSNDeleteNode()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
           //     ceConn.Close();
           //     ceConn.Dispose();
            }
        }


        private void fncUpdateUserBuddyStatus(string BuddName, string status)
        {
         //   SqlCeConnection ceConn = new SqlCeConnection(ClientConnectionString);
            try
            {
           //     ceConn.Open();
                //string strCommand = "Select Count(*) From User_BuddyList Where UserName = '" + userName + "' and BuddyName = '" + BuddName + "'";

                //SqlCeCommand cmd = new SqlCeCommand("SELECT COUNT(*) FROM User_BuddyList WHERE (UserName = '" + VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName + "') AND (BuddyName = '" + BuddName + "')", ceConn);
                //object i = cmd.ExecuteScalar();
                //if (int.Parse(i.ToString()) > 0)
                //{
                //    cmd = new SqlCeCommand("Update User_BuddyList Set BuddyStatus='" + status + "' Where (UserName = '" + VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName + "') AND (BuddyName = '" + BuddName + "')", ceConn);
                //    cmd.ExecuteNonQuery();
                //}
                OpenConnection();
                SqlCeCommand cmd = new SqlCeCommand("Update User_BuddyList Set BuddyStatus='" + status + "' Where BuddyName = '" + BuddName + "'", LocalSQLConn);
                cmd.ExecuteNonQuery();
           //     ceConn.Close();
           //     ceConn.Dispose();
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "fncUpdateUserBuddyStatus()--:--BootStrapdomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
             //   ceConn.Close();
             //   ceConn.Dispose();
            }
        }

        private void fncUpdateBuddyStatus(string userName, string BuddName, string status)
        {
         //   SqlCeConnection ceConn = new SqlCeConnection(ClientConnectionString);
            try
            {
            //    ceConn.Open();
                //string strCommand = "Select Count(*) From User_BuddyList Where UserName = '" + userName + "' and BuddyName = '" + BuddName + "'";
                OpenConnection();
                SqlCeCommand cmd = new SqlCeCommand("SELECT COUNT(*) FROM User_BuddyList WHERE (UserName = '" + userName + "') AND (BuddyName = '" + BuddName + "')", LocalSQLConn);
                object i = cmd.ExecuteScalar();
                if (int.Parse(i.ToString()) > 0)
                {
                    cmd = new SqlCeCommand("Update User_BuddyList Set BuddyStatus ='" + status + "' Where (UserName = '" + userName + "') AND (BuddyName = '" + BuddName + "')", LocalSQLConn);
                    cmd.ExecuteNonQuery();
                }
                else
                {
                    string str = "insert into User_BuddyList(UserName,BuddyName,BuddyStatus) values(@UserName,@BuddyName,@BuddyStatus) ";
                    cmd = new SqlCeCommand(str);
                    cmd.Connection = LocalSQLConn;

                    cmd.Parameters.AddWithValue("@UserName", userName);
                    cmd.Parameters.AddWithValue("@BuddyName", BuddName);
                    cmd.Parameters.AddWithValue("@BuddyStatus", status);
                    cmd.ExecuteNonQuery();

                }
            //    ceConn.Close();
             //   ceConn.Dispose();
            }

            catch (Exception ex)
            {
                ex.Data.Add("My Key", "fncUpdateBuddyStatus()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            //    ceConn.Close();
            //    ceConn.Dispose();
            }

        }

        void OpenConnection()
        {
            try
            {
                if (LocalSQLConn.State != ConnectionState.Open)
                {
                    LocalSQLConn.Open();
                }
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "OpenConnection()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }

        }

        #endregion
        // End Meet Code.

        private void StartUpload()
        {
            try
            {
                clsPresentationUpload c = new clsPresentationUpload();
            }
            catch (Exception ex)
            {
                //MessageBox.Show("StartUpload " + exp.Message);
                ex.Data.Add("My Key", "StartUpload()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (objHttpBootStrap != null)
            {
                objHttpBootStrap = null;
            }
            if (npsBootStrapServer != null)
            {
                npsBootStrapServer.CloseServer();
                npsBootStrapServer = null;
            }
            if (npsBootStrapPredictviveServer != null)
            {
                npsBootStrapPredictviveServer.CloseServer();
                npsBootStrapPredictviveServer = null;
            }
            if (npsBootStrapPBXServer != null)
            {
                npsBootStrapPBXServer.CloseServer();
                npsBootStrapPBXServer = null;
            }
            if (npsBootStrapActiveCallReportService != null)
            {
                npsBootStrapActiveCallReportService.CloseServer();
                npsBootStrapActiveCallReportService = null;
            }
            if (npsBootStrapActiveAgentReportService != null)
            {
                npsBootStrapActiveAgentReportService.CloseServer();
                npsBootStrapActiveAgentReportService = null;
            }
            if (npsRecordingServer != null)
            {
                npsRecordingServer.CloseServer();
                npsRecordingServer = null;
            }
            //if (Conn != null)
            //{
            //    Conn = null;
            //}
            //if (sqlcmd != null)
            //{
            //    sqlcmd = null;
            //}
            //if (dt != null)
            //{
            //    dt = null;
            //}
            if (strCurrentMachineIP != null)
            {
                strCurrentMachineIP = null;
            }
            if (appPath != null)
            {
                appPath = null;
            }
            if (awClientConnectionString != null)
            {
                awClientConnectionString = null;
            }
        }

        #endregion


        //code for super node checking and deleting
        #region shilpa code
        //5-feb-2008 
        //for supernode checking
        private Boolean checkSuperNodeAvailable(string currentSuperNodeIP)
        {
            //currentSuperNodeIP is ip of super node to check existance
            //net check method
            Uri objuri = new Uri("http://" + currentSuperNodeIP + ":" + "80/HttpSuperNode");
            //System.Windows.MessageBox.Show(currentSuperNodeIP + ":" + ":80/HttpSuperNode");
            System.Net.WebRequest objWebReq = System.Net.WebRequest.Create(objuri);
            System.Net.WebResponse objResp;
            try
            {
                objResp = objWebReq.GetResponse();
                objResp.Close();
                return true;
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "StartUpload()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
                //MessageBox.Show(ex.Message);
                return false;
            }
        }
        //6-feb-2008 
        private void adjustSuperNode(string currentSuperNodeIP)
        {
            try
            {
                //6-feb-2008 
                ////select nodes whoes super node is not available now
                //SqlCeDataAdapter sqlDataAdapNode = null;
                //DataTable dtNode = new DataTable();
                ////SqlCeCommand sqlcmdSelNode = new SqlCeCommand("Select * from SuperNode_Node_Info where SuperNodeIP= '" + objSuperNodeInfo.SuperNodeIP + "'");
                //sqlDataAdapNode = new SqlCeDataAdapter("Select Id from SuperNode_Node_Info where SuperNodeIP= '" + objSuperNodeInfo.SuperNodeIP + "'", Conn);
                //sqlDataAdapNode.Fill(dtNode);
              //  SqlCeConnection conn = new SqlCeConnection(awClientConnectionString);
                SqlCeCommand sqlcmd = null;
                //delete the super node entry from the table 
              //  conn.Open();

                sqlcmd = new SqlCeCommand("Select SuperNodeName from SuperNode_Info where SuperNodeIP='" + currentSuperNodeIP + "'");
                sqlcmd.Connection = LocalSQLConn;
                object objName = sqlcmd.ExecuteScalar();

                sqlcmd = new SqlCeCommand("Delete from SuperNode_Info where SuperNodeIP='" + currentSuperNodeIP + "'");
                sqlcmd.Connection = LocalSQLConn;
                int totDel = sqlcmd.ExecuteNonQuery();

                // **
                if (lstsSuperNodeInfo.Contains(currentSuperNodeIP))
                {
                    lstsSuperNodeInfo.Remove(currentSuperNodeIP);
                }
                else if(lstsSuperNodeInfo.Contains((string) objName))
                {
                    lstsSuperNodeInfo.Remove((string)objName);
                }


              //  conn.Close();
              //  conn.Dispose();
                //Reassign super node to "selected" node 
                //assign all its  node to the another super node 
                //for (int i = 0; i < dtNode.Rows.Count; i++)
                //{

                //}


            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "adjustSuperNode()--:--BootStrapDomain.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);            
            }

        }
        #endregion

        ~BootstrapServiceDomain()
        {
            Dispose();
        }

    }
}
